package com.yz.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.yz.pojo.Blog;
import com.yz.pojo.BlogCategory;
import com.yz.pojo.dto.BlogDto;
import com.yz.service.BlogService;
import com.yz.service.CategoryService;
import com.yz.service.TagService;
import com.yz.util.Result;
import com.yz.util.ResultGenerator;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagService tagService;

    /**
     * 博客管理展示博客
     *
     * @param model
     * @return
     */
    @RequestMapping("/blog")
    public String blog(Model model) {
        List<BlogDto> allBlog = blogService.queryAllBlog();
        model.addAttribute("allBlog", allBlog);
        return "admin/blog";
    }

    /**
     * 根据关键字查询博客
     *
     * @param keyword
     * @param model
     * @return
     */
    @RequestMapping("/blog/{keyword}")
    public String search(@PathVariable("keyword") String keyword, Model model) {

        System.out.println(keyword);
        List<BlogDto> allBlog = blogService.queryBlogByTitleOrCategory(keyword);
        model.addAttribute("allBlog", allBlog);
        return "admin/blog";
    }

    /**
     * 根据id批量删除博客
     *
     * @param ids
     * @return
     */
    @RequestMapping("/blog/delete")
    @ResponseBody
    public Result delete(@RequestParam("ids") Integer[] ids) {
        if (blogService.deleteBlog(ids) > 0) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("删除失败！");
        }
    }

    /**
     * 保存博客，修改或者增加博客
     *
     * @param blogTitle
     * @param blogCoverImage
     * @param blogContent
     * @param blogCategoryId
     * @param blogTags
     * @param blogStatus
     * @param enableComment
     * @return
     */
    @RequestMapping("/blog/save")
    @ResponseBody
    @Transactional
    public Result save(@RequestParam("blogId") Integer blogId, @RequestParam("blogTitle") String blogTitle, @RequestParam("blogCoverImage") String blogCoverImage,
                       @RequestParam("blogContent") String blogContent, @RequestParam("blogCategoryId") Integer blogCategoryId,
                       @RequestParam("blogTags") String blogTags, @RequestParam("blogStatus") Integer blogStatus,
                       @RequestParam("enableComment") Integer enableComment) {

        Blog blog = new Blog();
        // 根据分类 id 获取分类名
        String blogCategoryName = categoryService.queryNameById(blogCategoryId);
        // 如果 blogId != 0 则表示是修改博客
        if (blogId != 0) {
            // 根据 blogId 查询博客
            blog = blogService.queryBlogById(blogId);
        }
        // 查到了博客则表示是修改博客
        if(blog.getBlogId() != null){
            blog.setBlogTitle(blogTitle);
            blog.setBlogCoverImage(blogCoverImage);
            blog.setBlogContent(blogContent);
            blog.setBlogCategoryId(blogCategoryId);
            blog.setBlogCategoryName(blogCategoryName);
            blog.setBlogTags(blogTags);
            blog.setBlogStatus(blogStatus);
            blog.setEnableComment(enableComment);

            if (blogService.updateBlog(blog) > 0) {
                return ResultGenerator.genSuccessResult();
            } else {
                return ResultGenerator.genFailResult("保存失败");
            }
        }
        // 从这里开始表示是新增博客
        if (!Strings.isEmpty(blogTitle))
            blog.setBlogTitle(blogTitle);
        if (!Strings.isEmpty(blogCoverImage))
            blog.setBlogCoverImage(blogCoverImage);
        if (!Strings.isEmpty(blogContent))
            blog.setBlogContent(blogContent);
        if (blogCategoryId != 0)
            blog.setBlogCategoryId(blogCategoryId);
        if (!Strings.isEmpty(blogCategoryName))
            blog.setBlogCategoryName(blogCategoryName);
        if (!Strings.isEmpty(blogTags))
            blog.setBlogTags(blogTags);
        blog.setBlogStatus(blogStatus);
        blog.setEnableComment(enableComment);

        if (blogService.saveBlog(blog) > 0) {
            // 将标签分割成多个
            String[] tags = blogTags.split(",");
            // 将标签插入到数据库中，一次可以插入多个标签
            tagService.insertTags(tags);
            // 查询这一篇博客的标签 id
            Integer[] tagIds = tagService.queryIdByNames(tags);
            // 更新博客和标签的联系表 blog_tag
            blogService.updateBlogTag(blog.getBlogId(),tagIds);
            // 返回成功信息
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("文章标题重复，保存失败");
        }

    }

    @RequestMapping("/blog/update/{blogId}")
    public String update(@PathVariable("blogId") Integer blogId, Model model) {

        List<BlogCategory> categories = categoryService.queryAllCategory();
        model.addAttribute("categories", categories);
        Blog blog = blogService.queryBlogById(blogId);
        model.addAttribute("blog", blog);
        return "admin/edit";
    }

    // 编写博客时添加图片功能
    @RequestMapping("/blog/upload")
    @ResponseBody
    public JSONObject upload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws URISyntaxException {
        // 获取上传的时候图片名 xxx.jpg
        String trueFileName = file.getOriginalFilename();
        // 以 . 进行分割，得到文件的后缀
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
        // 用随机数给文件重新命名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffix);
        String fileName = tempName.toString();
        // 图片保存在电脑的绝对路劲
        String path = "E:/自写项目/administrator-demo/src/main/resources/static/admin/img/upload/blogContentMap/";
        // 访问图片的路径，配置了虚拟路径，所以不需要给出绝对路径
        URI uri = new URI(request.getRequestURL() + "");
        String fileUrl = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null) + "/upload/blogContentMap/" + fileName;

        // 创建文件夹
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        // 保存图片到文件夹
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 保存成功返回JSON对象，editormd 要求格式如下：
        JSONObject res = new JSONObject();
        res.put("url", fileUrl);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }

    // 博客封面图
    @PostMapping("/blog/blogCoverImage")
    @ResponseBody
    public JSONObject blogCoverImage(@RequestParam("file") MultipartFile file, Model model) {
        // 返回JSON 对象
        JSONObject res = new JSONObject();
        // 判断文件是否超过20M
        if (file.getSize() > 1024 * 1024 * 20) {
            res.put("isSuccess", 0);
            res.put("message", "file too large");
            return res;
        }
        // 获取上传的时候图片名 xxx.jpg
        String fileName = file.getOriginalFilename();
        // 以 . 进行分割，得到文件的后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 用随机数给文件重新命名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffix);
        String newFileName = tempName.toString();
        // 自定义路径
        String path = "E:/自写项目/administrator-demo/src/main/resources/static/admin/img/upload/blogCoverImage/";
        // 图片 路径 + 名字
        File dest = new File(path + newFileName);
        // 访问图片的路径，配置了虚拟路径，所以不需要给出绝对路径
        String fileUrl = "/upload/blogCoverImage/" + newFileName;
        try {
            // 保存图片
            file.transferTo(dest);
            // 成功就返回 isSuccess = 1
            res.put("url", fileUrl);
            res.put("isSuccess", 1);
            res.put("message", "upload success!");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("isSuccess", 0);
            res.put("message", "upload failed!");
            return res;
        }
        return res;
    }

}
